package com.songyang.mqttandothers.mqttCore;

/**
 * Created by Administrator on 17-2-10.
 */

import com.songyang.mqttandothers.common.MqttConfiguration;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.Scanner;

/**
 * Title:Server 这是发送消息的服务端
 * Description: 服务器向多个客户端推送主题，即不同客户端可向服务器订阅相同主题
 *
 * @author Unclue_liu
 */
public class ServerMQTT {

    //tcp://MQTT安装的服务器地址:MQTT定义的端口号
//    public static final String HOST = "tcp://192.168.1.77:1883";
    public final String HOST = MqttConfiguration.HOST;
    //定义一个主题
    public String TOPIC = "yd";
    //定义MQTT的ID，可以在MQTT服务配置中指定
    private  String clientid="123456" ;
    private String msg;
    private MqttClient client;
    private static MqttTopic topic11;
//    private String userName = "mqtt";  //非必须
//    private String passWord = "mqtt";  //非必须

    private static MqttMessage message;

    /**
     * 构造函数
     *
     * @throws MqttException
     */
    public ServerMQTT(String topic, String msg) throws MqttException {
        this.TOPIC = topic;
        this.msg = msg;
        // MemoryPersistence设置clientid的保存形式，默认为以内存保存
        client = new MqttClient(HOST, clientid, new MemoryPersistence());
        connect();
    }

    public ServerMQTT() {

    }

    /**
     * 用来连接服务器
     */
    private void connect() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
//        options.setUserName(userName);
//        options.setPassword(passWord.toCharArray());
        // 设置超时时间
        options.setConnectionTimeout(100);
        // 设置会话心跳时间
        options.setKeepAliveInterval(20);
        try {
//            client.setCallback(new PushCallback());
            client.connect(options);
            topic11 = client.getTopic(TOPIC);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param topic
     * @param message
     * @throws MqttPersistenceException
     * @throws MqttException
     */
    public void publish(MqttTopic topic, MqttMessage message) throws MqttPersistenceException,
            MqttException {
        MqttDeliveryToken token = topic.publish(message);
        token.waitForCompletion();
    }


    public void sendMessage(String clientId, String msg) throws Exception {
        ServerMQTT server = new ServerMQTT();
        server.message = new MqttMessage();
        server.message.setQos(1);  //保证消息能到达一次
        server.message.setRetained(true);
//        String str = "{\"clientId\":\"" + clientId + "\",\"msg\":\"" + msg + "\"}";
             server.message.setPayload(msg.getBytes());
        try {
            publish(server.topic11, server.message);

            //断开连接
//            server.client.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            sendMessage(clientid, msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            Scanner sc = new Scanner(System.in);
            while (true){
                new ServerMQTT("yd",sc.nextLine()).start();
                System.out.println("发送成功！");
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}

